package com.common.thread;

import com.common.vo.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.io.UnsupportedEncodingException;

/**
 * 推送mqtt消息
 * 
 * @author 57300
 *
 */
public class MqttSendMsgThread implements Runnable {

	private String clientId;
	private String message;
	private MqttMessage mqttMessage;

	public MqttSendMsgThread(MqttMessage mqttMessage, String clientId, String message) {
		this.mqttMessage = mqttMessage;
		this.clientId = clientId;
		this.message = message;
	}

	@Override
	public void run() {
		sendMessage(clientId, message);
	}

	/**
	 * 发送消息【客户端/服务端】
	 * @param clientId
	 * @param message
	 * @return
	 */
	public String sendMessage(String clientId, String message) {
		try {
			if (this.mqttMessage.getClient() == null || !this.mqttMessage.getClient().isConnected()) {
				//this.mqttMessage.connect();
			}
			if (clientId == null) {
				clientId = "";
			}
			if (message != null && !message.equals("")) {
				// 发布自己的消息
				this.mqttMessage.getClient().publish(this.mqttMessage.getMyTopic() + "/" + clientId, message.getBytes("UTF-8"), 0, false);
			} else {
				return "消息内容不能未空";
			}
		} catch (MqttException e) {
			e.printStackTrace();
			return "消息推送异常";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
            /*if (client != null) {
                try {
                    client.disconnect();
                } catch (MqttException e1) {
                    e1.printStackTrace();
                }
            }
            client = null;*/
		}
		return "消息推送成功";
	}


}
